<template>
  <div class='page'>
    <van-nav-bar :title='$t("m.header.memberInfo")' left-arrow @click-left='onBack' />
    <input id='uploadFileInput' ref='inputUpload' type='file' accept='image/*' @change='uploadInputchange'>
    <div class='avatar_box' @click='onAvatar()'>
      <img v-if='userInfo.avatar' :src='userInfo.avatar'>
      <img v-else src='https://zszken.cdn.bcebos.com/static/baby-na.png'>
    </div>
    <van-cell-group>
      <van-cell :title='$t("m.info.name")' :value='userInfo.user' />
      <van-cell class='sex' :title='$t("m.info.sex")' :value='userInfo.sex' @click='show = true' />
    </van-cell-group>
    <div v-if='userInfo.user' class='pageBottom van-button--danger' @click='onLogOut'>
      <span class='tabbar-label'>{{ $t('m.set.logout') }}</span>
    </div>
    <van-actionsheet v-model='show' :actions='actions' @select='onSelect' />
  </div>
</template>

<script>
import { apiEditUser, apiLogOut } from '@/api/user.js'
import { apiGetQiNiuToken } from '@/api/upload.js'
import axios from 'axios'
import { NavBar, Cell, CellGroup, Actionsheet, Toast } from 'vant'
import { mapActions, mapState, mapMutations } from 'vuex'
export default {
  metaInfo () {
    return {
      title: this.$t('m.meta.ininfogo.title'),
      meta: [
        {
          name: this.$t('m.meta.info.name'),
          content: this.$t('m.meta.info.content'),
        },
      ],
    }
  },
  computed: {
    ...mapState(['userInfo']),
  },
  data () {
    return {
      show: false,
      actions: [
        {
          name: '男',
        },
        {
          name: '女',
        },
      ],
      uploadToken: {
        token: '',
      },
      coverJoinUrl: '',
      apiParams: {},
      sex: '',
      domain: '',
    }
  },
  components: {
    [NavBar.name]: NavBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Actionsheet.name]: Actionsheet,
    [Toast.name]: Toast,
  },
  beforeRouteUpdate (to, from, next) {
    next(() => {
      console.log(to)
      console.log(from)
    })
  },
  beforeMount () {
    this.getUserInfo()
  },
  methods: {
    ...mapActions(['getUserInfo', 'setData']),
    ...mapMutations({
      resetUser: 'REREST_USER',
    }),
    onRead (file) {
      console.log(file)
      this.$refs.avatar.src = file.content
      let data = new FormData()
      data.append('token', this.uploadToken.token)
      data.append('file', file.content)
      const axiosInstance = axios.create({ withCredentials: false })
      console.log('data: ', data)
      axiosInstance({
        method: 'POST',
        url: 'http://upload.qiniu.com/', // 上传地址
        data: data,
        timeout: 30000, // 超时时间，因为图片上传有可能需要很久
      })
        .then(data => {
          console.log(data)
        })
        .catch(function (err) {
          console.log('err', err)
        })
    },
    async onSelect (item) {
      console.log(item.name)
      let sex = ''
      this.show = false
      this.userInfo.sex = item.name
      item.name == '男' ? (sex = '男') : (sex = '女')
      await apiEditUser(sex, this.userInfo.avatar)
    },
    async onUpload () {
      const res = await apiGetQiNiuToken()
      this.uploadToken.token = res.data.token
      this.domain = res.data.domain
    },
    onLogOut () {
      apiLogOut().then(() => {
        Toast(this.$t('m.message.userLogOut'))
        this.$router.go(-1)
        this.resetUser()
        this.setData({
          login: false,
        })
      })
    },
    onAvatar () {
      this.onUpload()
      this.$refs.inputUpload.dispatchEvent(new MouseEvent('click'))
    },
    // 触发input change事件
    uploadInputchange () {
      let file = document.getElementById('uploadFileInput').files[0] // 选择的图片文件
      this.uploadImgToQiniu(file)
    },
    // 上传图片到七牛
    uploadImgToQiniu (file) {
      this.apiParams = {}
      console.log('1')
      const axiosInstance = axios.create({ withCredentials: false }) // withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
      let data = new FormData()
      data.append('token', this.uploadToken.token)// 七牛需要的token，叫后台给，是七牛账号密码等组成的hash
      data.append('file', file)
      axiosInstance({
        method: 'POST',
        url: 'http://upload.qiniup.com/', // 上传地址
        data: data,
        timeout: 30000, // 超时时间，因为图片上传有可能需要很久
      })
        .then(data => {
          console.log('data', data)
          const clone = Object.assign({}, this.userInfo)
          clone.avatar = `${this.domain}${data.data.key}`
          this.avatar = `${this.domain}${data.data.key}`
          this.setData({
            userInfo: clone,
          })
          this.editUser()
          document.getElementById('uploadFileInput').value = '' // 上传成功，把input的value设置为空，不然 无法两次选择同一张图片
        })
        .catch(function (err) {
          console.log('errs', err)
        })
    },
    async editUser () {
      await apiEditUser(this.userInfo.sex, this.avatar)
    },
  },
}
</script>

<style lang='scss' scoped>
.container {
  text-align: center;
  img {
    margin-top: 30px;
  }
  p {
    margin-top: 30px;
    font-size: 28px;
  }
}
.avatar_box {
  text-align: center;
  cursor: pointer;
  img {
    width: 100px;
    height: 100px;
  }
}
.sex {
  cursor: pointer;
}
#uploadFileInput {
  display: none;
}
.pageBottom {
  position: fixed;
  bottom: 0;
  width: 100%;
  line-height: 40px;
  color: $base_color;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
}
.page {
  :global(.van-popup--bottom) {
    width: 640PX !important;
    left: 50% !important;
  }
  :global(.van-overlay) {
    width: 640PX !important;
    left: 50% !important;
    margin-left: -320PX !important;
  }
}
</style>
